//
//  JKHomeViewController.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/6/29.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit

private let originalCellId = "originalCellId"

private let retweetedCellId = "retweetedCellId"

class JKHomeViewController: JKBaseViewController {

//    private lazy var statusList = [String]()
    private lazy var listViewModel = JKStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    
    @objc private func showFriends() {
        
        let vc = JKDemoViewController()
        
//        vc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 加载数据
    override func loadData() {

//        print("开始加载数据")
//        print("开始加载数据 \(JKNetworkManager.shared)")
//        
//        listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
//            
//            print("刷新表格")
//        
//            print("加载数据结束")
//            // 结束刷新控件
//            self.refreshControl?.endRefreshing()
//            
              // 恢复上拉刷新
//            self.isPullup = false
//          
              // 刷新表格
//            if shouldRefresh {
//            self.tableView?.reloadData()

//              print("准备刷新")

//            }
        print("准备刷新")
        // Xcode 8.0 的刷新控件，beginRefreshing 方法，什么都不显示！
        refreshControl?.beginRefreshing()
        
        // 模拟演示加载数据
        DispatchQueue.main.after(when: DispatchTime.now() + 2) {
            self.listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
                
                print("加载数据结束)")
                // 结束刷新控件
                self.refreshControl?.endRefreshing()
                // 恢复上拉刷新标记
                self.isPullup = false
                
                // 刷新表格
                if shouldRefresh {
                    self.tableView?.reloadData()
                }
            }
        }
    }
}

// MARK: - 数据源和代理方法
extension JKHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let vm = listViewModel.statusList[indexPath.row]
        
        let cellId = (vm.status?.retweeted_status != nil) ? retweetedCellId : originalCellId
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! JKStatusCell

        cell.viewModel = vm
        
        // --- 设置代理 ---
        // 如果用 block 需要在数据源方法中, 给每一个 cell 设置 block
        // cell.completionBlock = { // ...}
        // 设置代理只是传递一个指针地址
        cell.delegate = self
        
        return cell
    }
    
    
    /// 父类必须实现代理方法，子类才能够重写，Swift 3.0 才是如此，2.0 不需要
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        // 1. 根据 indexPath 获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        // 2. 返回计算好的行高
        return vm.rowHeight
    }

}

// MARK: - JKStatusCellDelegate
extension JKHomeViewController: JKStatusCellDelegate {
   
    func statusCellDidSelectedURLString(cell: JKStatusCell, urlString: String) {
        
//        print(urlString)
        let vc = JKWebViewController()
        
        vc.urlString = urlString
        
        navigationController?.pushViewController(vc, animated: true)

    }
}



extension JKHomeViewController {
    
    // 重写父类方法
    override func setupTableView() {
       
        super.setupTableView()
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
//        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    
        tableView?.register(UINib(nibName: "JKStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        
        tableView?.register(UINib(nibName: "JKStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
        
        
//        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300

        tableView?.separatorStyle = .none
        
        setupNavTitle()
        
    }

    private func setupNavTitle() {
    
        let title = JKNetworkManager.shared.userAccount.screen_name
        
        let button = JKTitleButton(title: title)
    
        navItem.titleView = button
        
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    
    @objc func clickTitleButton(btn: UIButton) {
        
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
    
}


